package com.fate.framework.utils;

import javax.annotation.Nonnull;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;

/**
 * @author: Ten.X
 * @date: 2023-01-15 01:01
 */
@Repository
public class SpringUtil implements BeanFactoryPostProcessor {

  /** Spring应用上下文环境 */
  @Getter private static ConfigurableListableBeanFactory beanFactory;

  private static ApplicationContext applicationContext;

  @SuppressWarnings("unchecked")
  public static <T> T getBean(String name) throws BeansException {
    return (T) getBeanFactory().getBean(name);
  }

  public static <T> T getBean(Class<T> clazz, String beanName) {
    return applicationContext.getBean(beanName, clazz);
  }

  public static <T> T getBean(Class<T> clz) throws BeansException {
    return (T) getBeanFactory().getBean(clz);
  }

  @Override
  public void postProcessBeanFactory(@Nonnull ConfigurableListableBeanFactory beanFactory)
      throws BeansException {
    SpringUtil.beanFactory = beanFactory;
  }
}
